import Vue from "vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import App from "./App.vue";
import router from "./router";
import axios from 'axios'
import chsm from 'chsm-components'
import '../public/iconfont.css'

Vue.use(ElementUI);
Vue.use(chsm)

const BASE_URL = "http://localhost"

axios.defaults.baseURL = BASE_URL
axios.defaults.withCredentials = true
let bl = false
// axios请求拦截器
axios.interceptors.request.use(res => {
  bl = false;
  return res;
});
// axios响应拦截器
axios.interceptors.response.use(
  res => {
    // 200放行
    if (res.data.status === 200) {
      return res;
    } else {
      // bl为true时不再重复提示
      if (!bl) {
        bl = true;
        message(res.data.msg);
      }
      if (res.data.status === 300) {
        router.push("/login");
      }
      if (res.data.status === 301) {
        router.push("/MaLogin");
      }
      return res;
    }
  },
  error => {
    console.log(error);
    if (!bl) {
      message("服务器异常");
      bl = true;
    }
    return
})


Vue.prototype.axios = axios
Vue.prototype.baseUrl = BASE_URL
Vue.config.productionTip = false
const TITLE = "第二商城-"

let oldPath = null;

router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    oldPath = from;
  }
  if (
    to.path === "/" &&
    oldPath != null &&
    oldPath.path !== "/" &&
    oldPath.path !== "/register"
  ) {
    router.push({ path: oldPath.path, query: oldPath.query });
    oldPath = null;
  }
  if (to.meta.title) {
    document.title = TITLE + to.meta.title;
  }
  next();
});

let vm = new Vue({
  data: {
    cart: null,
    user: null
  },
  router,
  render: h => h(App)
}).$mount("#app");

function message(msg) {
  vm.$message({
    message: msg,
    type: "error",
    center: true
  });
}
